<template>
  <div>
    <div>
      <div class="cards">
        <el-button type="primary" style="margin-right: 10px" @click="handleAdd">
          <el-icon style="margin-right: 5px"><ShoppingTrolley /></el-icon>
          购买
        </el-button>
        <el-button type="warning" style="margin-left: -2px" @click="delBatch">批量删除</el-button>
      </div>
      <!--数据表-->
      <div class="cards" style="margin-top: 10px">
        <el-table :data="data.tableData" @selection-change="handleSelectionChange" stripe>
          <el-table-column type="selection" style="border: #666666; width: 10px"></el-table-column>
          <el-table-column label="药材名称" prop="name" />
          <el-table-column label="购买量(g)" prop="count" />
          <el-table-column label="金额(元/g)" prop="price_sum" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button @click="handleDelete(scope.row)" type="danger" :icon="Delete" style="padding: 5px 8px">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px">
          <el-pagination
              @current-change="load"
              @size-change="load"
              v-model:current-page="data.pageNum"
              v-model:page-size="data.pageSize"
              :page-sizes="[5, 10, 15, 20]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="data.total"
          ></el-pagination>
        </div>
      </div>
      <!--购买-->
      <el-dialog v-model="data.formVisible" title="新增订单信息" width="500" style="margin-top: 2%">
        <el-form :model="data.form" style="width: 400px; margin: 0 auto; display: flex; flex-direction: column; align-items: flex-start;">
          <!-- 设置label-width统一标签宽度 -->
          <el-form-item label="药材名称" label-width="80px" style="margin-top: 20px">
            <el-input v-model="data.form.name" autocomplete="off" style="width: 280px;" />
          </el-form-item>
          <el-form-item label="收货人" label-width="80px">
            <el-input v-model="data.form.receiver" autocomplete="off" placeholder="请输入收货人姓名" style="width: 280px;" />
          </el-form-item>
          <el-form-item label="手机号" label-width="80px">
            <el-input v-model="data.form.phone" autocomplete="off" placeholder="请输入手机号" style="width: 280px;" />
          </el-form-item>
          <el-form-item label="金额(元)" label-width="80px">
            <el-input v-model="data.form.price_sum" autocomplete="off" style="width: 280px;" />
          </el-form-item>
          <el-form-item label="下单日期" label-width="80px">
            <div class="demo-date-picker">
              <div class="block">
                <el-date-picker
                    v-model="data.form.create_date"
                    type="date"
                    placeholder="请选择下单日期"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="收货地址" label-width="80px">
            <el-input
                v-model="data.form.address"
                maxlength="30"
                style="width: 280px; height: 80px; resize: none; overflow-y: auto;"
                placeholder="请输入收货地址"
                show-word-limit
                type="textarea"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="data.formVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">下 单</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { ShoppingTrolley, Delete } from "@element-plus/icons-vue";
import { ref } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

// 定义日期格式化函数
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  userList: [],
  formVisible: false,
  form: {},
  ids: [],
});

const load = () => {
  request.get('/shop/searchOrders', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
    }
  }).then((res) => {
    data.tableData = res.data.data;
    data.total = res.data.total;
  });
};
load();

// 重置
const rest = () => {
  data.name = null;
  load();
};

// 新增
const handleAdd = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请先选择一个订单');
    return;
  }
  const selectedRow = data.tableData.find((row) => row.id === data.ids[0]);
  if (selectedRow) {
    data.formVisible = true;
    data.form = {
      ...data.form,
      name: selectedRow.name,
      price_sum: selectedRow.price_sum,
      // 设置下单日期为当前日期并格式化为 YYYY-MM-DD
      create_date: formatDate(new Date())
    };
  }
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '温馨提示', { type: 'warning' }).then(() => {
    request.delete('shop/deleteShopCar/' + row.id).then((res) => {
      console.log(res);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.warning('已经被禁用，不可以进行删除');
      }
    });
  }).catch();
};

// 批量删除
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择数据');
    return;
  }
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '温馨提示', { type: 'warning' }).then(() => {
    request.delete('shop/deleteBatchOrder', { data: data.ids }).then((res) => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.message);
      }
    });
  }).catch();
};

// 多选
const handleSelectionChange = (rows) => {
  console.log(rows);
  data.ids = rows.map((row) => row.id);
  console.log(data.ids);
};

const value = ref('');

// 下单方法
const save = () => {
  const { name, receiver, phone, price_sum, address, create_date } = data.form;
  if (!name || !receiver || !phone || !price_sum || !address || !create_date) {
    ElMessage.warning('请填写完整的订单信息');
    return;
  }
  // 这里添加实际下单的请求逻辑，比如发送post请求到后端
  request.post('order/addOrder', data.form).then((res) => {
    console.log(data.form);
    if (res.code === 200) {
      ElMessage.success('下单成功');
      data.formVisible = false;
      // 找到下单对应的行的 id
      const selectedRowId = data.ids[0];
      // 调用后端删除接口从数据库中删除数据
      request.delete('shop/deleteShopCar/' + selectedRowId).then((deleteRes) => {
        if (deleteRes.code === 200) {
          // 重新加载数据
          load();
        } else {
          ElMessage.error('数据库删除失败，请稍后重试');
        }
      }).catch((deleteError) => {
        ElMessage.error('数据库删除失败，请稍后重试');
        console.error(deleteError);
      });
    } else {
      ElMessage.error(res.message);
    }
  }).catch((error) => {
    ElMessage.error('下单失败，请稍后重试');
    console.error(error);
  });
  console.log('模拟下单，表单数据：', data.form);
};
</script>

<style scoped>
.cards {
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 8px rgba(0, 0, 0, .12);
}
</style>